<template>
  <PopList :title="'积水动画'" :showButton="true" @close="destroy" @ok="createWaterEffect">
    <!-- <div class="form-item">
      <span>积水区域:</span>
      <button @click="startDrawWater" :class="{active: isDrawing}">绘制区域</button>
    </div> -->
    <LabelInput v-model="waterHeight" :inputType="'number'" :label="'积水高度'" :min="0" :max="1000" :step="0.1"></LabelInput>
    <LabelInput v-model="targetHeight" :inputType="'number'" :label="'最大高度'" :min="0" :max="1000" :step="0.1"></LabelInput>
    <LabelInput v-model="waterAlpha" :inputType="'number'" :label="'透明度'" :min="0" :max="1" :step="0.01"></LabelInput>
    <LabelInput v-model="waterColor" :inputType="'color'" :label="'水面颜色'" :min="0" :max="1" :step="0.01"></LabelInput>
<!--    <div class="form-item">-->
<!--      <span>水面颜色:</span>-->
<!--      <input type="color" v-model="waterColor" />-->
<!--    </div>-->
    <LabelInput v-model="animationSpeed" :inputType="'number'" :label="'动画速度'" :min="0.1" :max="5" :step="0.1"></LabelInput>
  </PopList>
</template>

<script setup lang="ts">
import { ref, inject, onMounted, onBeforeUnmount, watch } from 'vue';
import { XbsjEarthUi } from "../../../scripts/xbsjEarthUi";
import PopList from "../../../components/PopList.vue";
import LabelInput from "../../../components/LabelInput.vue";
import { Message } from 'earthsdk-ui';
import * as Cesium from 'cesium';

const xbsjEarthUi = inject('xbsjEarthUi') as XbsjEarthUi;

// 水面参数
const waterHeight = ref(1.0);
const targetHeight = ref(20.0);
const waterAlpha = ref(0.6);
const waterColor = ref('#3498db');
const animationSpeed = ref(0.1);
const isDrawing = ref(false);

// 存储绘制的点
const drawnPoints = ref<number[][]>([]);
let handler: any = null;
let waterPrimitive: any = null;

// 开始绘制水面区域
const startDrawWater = () => {
    clearDrawing();
    isDrawing.value = true;
  
    const viewer = xbsjEarthUi.activeViewer?.innerViewer?.viewer;
    if (!viewer) {
        Message.error('viewer 未初始化');
        return;
    }
  
    drawnPoints.value = [];
    handler = new window.Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
  
    // 单击添加点
    handler.setInputAction((event: any) => {
        const cartesian = viewer.scene.pickPosition(event.position);
        if (cartesian) {
            const cartographic = window.Cesium.Cartographic.fromCartesian(cartesian);
            const longitude = window.Cesium.Math.toDegrees(cartographic.longitude);
            const latitude = window.Cesium.Math.toDegrees(cartographic.latitude);
            drawnPoints.value.push([longitude, latitude]);
        }
    }, window.Cesium.ScreenSpaceEventType.LEFT_CLICK);
  
    // 双击结束绘制
    handler.setInputAction(() => {
        isDrawing.value = false;
        if (handler) {
            handler.destroy();
            handler = null;
        }
        if (drawnPoints.value.length > 2) {
            // 确保多边形闭合
            drawnPoints.value.push([...drawnPoints.value[0]]);
            createWaterEffect();
        }
    }, window.Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK);
};

// 创建水面效果
const createWaterEffect = () => {
    destroy();
  
    const viewer = xbsjEarthUi.activeViewer?.innerViewer?.viewer;
    if (!viewer) {
        Message.error('viewer 未初始化');
        return;
    }
  
    // if (drawnPoints.value.length <= 2) {
    //   Message.warning('请先绘制积水区域');
    //   return;
    // }
  
    let areaCoor = [];
    for (let i = 0; i < drawnPoints.value.length; i++) {
        areaCoor.push(drawnPoints.value[i][0]);
        areaCoor.push(drawnPoints.value[i][1]);
        areaCoor.push(0);
    }
    const hexToRgb = (hex: string) => {
        const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
        return result ? {
            r: parseInt(result[1], 16),
            g: parseInt(result[2], 16),
            b: parseInt(result[3], 16)
        } : null;
    };

    const rgb = hexToRgb(waterColor.value);
    if (!rgb) {
        Message.error('颜色格式错误');
        return;
    }
    // 计算透明度（0-255）
    const alpha = Math.round(waterAlpha.value * 255);

    let waterEntity = viewer.entities.add({
        polygon: {
            // hierarchy: Cesium.Cartesian3.fromDegreesArrayHeights(areaCoor),
            hierarchy: new Cesium.PolygonHierarchy([
                Cesium.Cartesian3.fromDegrees(118.296957, 32.307046),
                Cesium.Cartesian3.fromDegrees(118.297008, 32.303089),
                Cesium.Cartesian3.fromDegrees(118.29956, 32.297089),
                Cesium.Cartesian3.fromDegrees(118.304248, 32.29982),
                Cesium.Cartesian3.fromDegrees(118.30971, 32.302973),
                Cesium.Cartesian3.fromDegrees(118.318273, 32.307989),
                Cesium.Cartesian3.fromDegrees(118.315322, 32.314587),
                Cesium.Cartesian3.fromDegrees(118.305255, 32.3093),
            ]),
            perPositionHeight: true,
            extrudedHeight: new Cesium.CallbackProperty(function () {
                //此处用属性回调函数，直接设置extrudedHeight会导致闪烁。
                waterHeight.value += animationSpeed.value;
                if (waterHeight.value > targetHeight.value) {
                    waterHeight.value = targetHeight.value; //给个最大值
                }
                console.log(waterHeight.value)
                return waterHeight.value;
            }, false),
            material: new Cesium.Color.fromBytes(rgb.r, rgb.g, rgb.b, alpha),
        },
    });
  
    Message.success('积水效果已应用');
};

// 清除水面
const destroy = () => {
    const viewer = xbsjEarthUi.activeViewer?.innerViewer?.viewer;
    if (!viewer) return;
  
    // 移除所有水面
    const primitives = viewer.scene.primitives;
    for (let i = 0; i < primitives.length; i++) {
        const primitive = primitives.get(i);
        if (primitive && primitive.appearance && primitive.appearance.material && 
        primitive.appearance.material.uniforms && primitive.appearance.material.uniforms.baseWaterColor) {
            primitives.remove(primitive);
            i--; // 因为删除了元素，所以索引减1
        }
    }
};

// 清除绘制状态
const clearDrawing = () => {
    isDrawing.value = false;
    if (handler) {
        handler.destroy();
        handler = null;
    }
};

// 监听参数变化，实时更新水面效果
// watch([waterHeight, waterAlpha, waterColor, animationSpeed], () => {
//   if (drawnPoints.value.length > 2) {
//     createWaterEffect();
//   }
// });

onMounted(() => {
    // 组件挂载时初始化
});

onBeforeUnmount(() => {
    // 组件卸载前清理资源
    clearDrawing();
    destroy();
});
</script>

<style scoped>
.form-item {
  margin-bottom: 10px;
  display: flex;
  align-items: center;
}

.form-item span {
  min-width: 70px;
}

button {
  padding: 4px 10px;
  background: #292e42;
  border: none;
  border-radius: 3px;
  color: white;
  cursor: pointer;
}

button:hover {
  background: #3a4056;
}

button.active {
  background: #1890ff;
}

input[type="color"] {
  width: 40px;
  height: 20px;
  border: none;
  cursor: pointer;
}
</style> 